package com.scp;

import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.TimePicker;

import com.actionbarsherlock.view.MenuItem;
import com.scp.modelo.Registro;
import com.scp.util.Util;

public class ActCadPonto extends ActCadBase {

	private TimePicker tpHora;
	private TextView tvData;
	
	private Date data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_cad_ponto);
		configControls();
		carregaCadastro();
	}
	
	private void configControls() {		
		tpHora = (TimePicker) findViewById(R.id_cad_ponto.tpHora);
		tpHora.setIs24HourView(true);
		
		tvData = (TextView) findViewById(R.id_cad_ponto.tvData);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			if (item.getItemId() == R.id_menu_gravacao.btGravar) {
				Registro registro = new Registro();
				if (this.id > -1) {
					registro.set_id(this.id);
				}
				
				registro.setData(data);	
				
				Date dataHora = Util.getDateTime(data, tpHora.getCurrentHour(), tpHora.getCurrentMinute(), 0);
				registro.setTempo(dataHora);
								
				if (registro.Gravar()) {
					Util.ToastShort(this, "Registro gravado");
					this.finish();
				} else {
					throw new Exception("Erro ao gravar");
				}
			}
		} catch (Exception e) {
			Util.ToastLong(this, e.getMessage());
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private void carregaCadastro() {
		Intent i = getIntent();
		if (i != null && i.getExtras() != null) {
			data = Util.stringToDate(i.getExtras().getString("Data"));
			tvData.setText(Util.dateToString(data, "EEE, dd MMM yyyy"));
			this.id = i.getExtras().getLong("id");
			
			Registro registro = new Registro();
			if (this.id > -1) {
				registro.set_id(this.id);
				registro.BuscarPorPk();
				tpHora.setCurrentHour(Util.getHour(registro.getTempo()));
				tpHora.setCurrentMinute(Util.getMinute(registro.getTempo()));
			}
			
		}
	}

}
